package cn.holy.app.xcddt.ui.activity.record

import android.app.Activity
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Handler
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.OrientationHelper
import androidx.recyclerview.widget.RecyclerView
import cn.holy.app.xcddt.R
import cn.holy.app.xcddt.app.App
import cn.holy.app.xcddt.app.GlideApp
import cn.holy.app.xcddt.domain.RecordBean
import cn.holy.app.xcddt.domain.RecordGroup
import cn.holy.app.xcddt.repository.RecordRepository
import cn.holy.app.xcddt.repository.UserRepository
import cn.holy.app.xcddt.ui.activity.base.BaseActivity
import cn.holy.app.xcddt.ui.activity.record.livedata.LocationLiveData
import cn.holy.app.xcddt.ui.activity.record.view.RecordAudioView
import cn.holy.app.xcddt.utils.StringUtil
import cn.jzvd.JZVideoPlayer
import cn.jzvd.JZVideoPlayerStandard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.location.AMapLocation
import com.orhanobut.logger.Logger
import com.qmuiteam.qmui.util.QMUIKeyboardHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.AlbumFile
import com.yanzhenjie.permission.Rationale
import com.yanzhenjie.permission.runtime.Permission
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import kotlinx.android.synthetic.main.activity_record.*
import java.io.File
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList


/**
 * Created by xiong on 18-2-23.
 */

@Route(path = "/app/record/detail")
open class RecordActivity : BaseActivity(), RecordAudioView.IRecordAudioListener {


    var mLocation: AMapLocation? = null


    //当前坐标

    private val maxRecordTime = DEFAULT_MAX_RECORD_TIME
    private val minRecordTime = DEFAULT_MIN_RECORD_TIME
    private var timer: Timer? = null
    private var timerTask: TimerTask? = null
    private var mainHandler: Handler? = null
    private var recordTotalTime: Long = 0
    private var audioFileName: String? = null
    private var isHasAudio = false
    private var mediaPlayer: MediaPlayer? = null
    private var checkedVideoList: ArrayList<AlbumFile> = ArrayList()
    private var commonAdapter: CommonAdapter<AlbumFile>? = null
    private var lastRecordGroup: RecordGroup? = null


    @Inject
    lateinit var recordRepository: RecordRepository


    @Inject
    lateinit var userRepos: UserRepository

    @Inject
    lateinit var locationLiveData: LocationLiveData

    var checkedPhotoList = ArrayList<AlbumFile>()


//    private val mRationale = Rationale { context, permissions, executor ->
//        val permissionNames = Permission.transformText(context, permissions)
//        val message = context.getString(R.string.message_permission_rationale, TextUtils.join("\n", permissionNames))
//        // 这里使用一个Dialog询问用户是否继续授权。
//
//        QMUIDialog.MessageDialogBuilder(context)
//                .setTitle("提示")
//                .setMessage(message)
//                .addAction("确定") { dialog, index ->
//                    // 如果用户继续：
//                    executor.execute()
//                }
//                .addAction("取消") { dialog, index ->
//                    // 如果用户中断：
//                    executor.cancel()
//                }
//                .show()
//    }
    private var liveRecord: LiveData<RecordBean>? = null
    private var record: RecordBean? = null
    private var countLocalRecord: Long = 0

    override fun initData() {
        lastRecordGroup = recordRepository.lastRecordGroup
        lastRecordGroup?.let {
            countLocalRecord = recordRepository.countLocalRecord(it.record_num)!!

        }

        val id = intent.getIntExtra("id",0)
        tv_address.text = "正在定位中..."
        if (id != 0) {
            liveRecord = recordRepository.loadRecord(id)
            liveRecord?.observe(this, Observer<RecordBean> { record ->
                this@RecordActivity.record = record
                Logger.d(record)
                et_message.setText(record?.message)
                tv_address.text = record?.address
                this.address = record?.address
                this.latitude = record?.latitude?.toDouble()
                this.longitude = record?.longitude?.toDouble()
                if (record?.photos != null) {
                    checkedPhotoList.clear()
                    record.photos!!.forEach { path: String ->
                        val albumfile = AlbumFile()
                        albumfile.path = path
                        albumfile.thumbPath = path
                        checkedPhotoList.add(albumfile)
                    }
                    photo_list.visibility = if (checkedPhotoList.size > 0) View.VISIBLE else View.GONE
                    commonAdapter?.notifyDataSetChanged()
                }
                if (record?.audio != null) {
                    audioFileName = record.audio
                    mediaPlayer = MediaPlayer()
                    mediaPlayer!!.setDataSource("file://$audioFileName")
                    mediaPlayer!!.prepare()
                    recordTotalTime = mediaPlayer!!.duration.toLong()
                    val string = String.format(" 倒计时 %s ", StringUtil.formatRecordTime(recordTotalTime, maxRecordTime))
                    horvoiceview.setText(string)
                    audio_content.visibility = View.VISIBLE
                } else {
                    audio_content.visibility = View.GONE
                }
                if (record?.video != null) {
                    val albumfile = AlbumFile()
                    albumfile.thumbPath = record.videoThumb!!
                    albumfile.path = record.video!!
                    checkedVideoList.add(albumfile)
                    video_content.visibility = if (checkedVideoList.size > 0) View.VISIBLE else View.GONE
                    GlideApp.with(this@RecordActivity).load(albumfile.thumbPath).centerCrop().into(video_thumb)
                }
            })
        } else {

            locationLiveData.observe(this, Observer<AMapLocation> { amLocation: AMapLocation? ->

                if (!amLocation?.address.isNullOrEmpty() && address == null) {
                    this.mLocation = amLocation
                    this.address = amLocation!!.address
                    this.latitude = amLocation.latitude
                    this.longitude = amLocation.longitude
                    tv_address.text = amLocation.address

                }
                Logger.d(amLocation)
            })
        }



        btn_recordAudio.setRecordAudioListener(this)
        mainHandler = Handler()
        setupRecordCount()
    }

    private var recordCount: Int = 0

    private fun setupRecordCount() {
//        lastRecordGroup?.let {
//            ApiClient.webService.recordCount(it.id).subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe({
//                        it.data?.let {
//                            recordCount = it
//                        }
//                    }, {}, {})
//
//        }
//    }
    }

    private var rightActionBtn: Button? = null

    private var latitude: Double? = null

    private var address: String? = null

    private var longitude: Double? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1010 && resultCode == Activity.RESULT_OK) {
            latitude = data?.getDoubleExtra("latitude", 0.0)
            longitude = data?.getDoubleExtra("longitude", 0.0)
            address = data?.getStringExtra("address")
            tv_address.text = address


        }
    }


    override fun initView() {

        App.appComponent.inject(this)
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        top_bar.setTitle(R.string.action_record).setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        top_bar.addLeftImageButton(R.mipmap.ic_back, R.id.action_close).setOnClickListener({ finish() })
        rightActionBtn = top_bar.addRightTextButton(R.string.action_save, R.id.action_save)
        rightActionBtn?.setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        rightActionBtn?.setOnClickListener({ saveRecord() })

        QMUIKeyboardHelper.setVisibilityEventListener(this, { isOpen ->
            if (isOpen) {
                record_audio_panel.visibility = (View.GONE)
            }
        })
        val layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        photo_list.layoutManager = (layoutManager)

        commonAdapter = object : CommonAdapter<AlbumFile>(this, R.layout.layout_photo_item, checkedPhotoList) {

            override fun convert(holder: ViewHolder, albumFile: AlbumFile, position: Int) {
                val photo = holder.getView<ImageView>(R.id.iv_thumb)


                photo.setOnClickListener {
                    val photos = ArrayList<String>()
                    checkedPhotoList.forEach { item ->
                        photos.add(item.path)
                    }
                    Album.gallery(this@RecordActivity)
                            .checkedList(photos)
                            .requestCode(1001) // 请求码，会在listener中返回。
                            .checkable(false) // 是否有浏览时的选择功能。
                            .onResult { requestCode, result ->
                            }
                            .onCancel { requestCode, result -> }

                            .start() // 千万不要忘记调用start()方法。
                }
                GlideApp.with(this@RecordActivity).load("file://" + albumFile.path).placeholder(R.mipmap.loading).centerCrop().into(photo)
                holder.getView<ImageView>(R.id.btn_delete).setOnClickListener({
                    checkedPhotoList.removeAt(position)
                    photo_list.visibility = if (checkedPhotoList.size > 0) View.VISIBLE else View.GONE
                    commonAdapter!!.notifyDataSetChanged()
                })
            }
        }
        photo_list.adapter = (commonAdapter)

        initListener()
        video_content.setOnClickListener {
//            if (checkedVideoLis)
            JZVideoPlayerStandard.startFullscreen(this,
                    JZVideoPlayerStandard::class.java,checkedVideoList[0].path,"视频预览")
        }
    }

    private fun initListener() {
        btnChoosePhoto.setOnClickListener { choosePhoto() } //选择图片
        btn_showRecord.setOnClickListener { showRecord() }
        btn_recordVideo.setOnClickListener { recordVideo() }
        video_content.setOnClickListener { }
        audio_content.setOnClickListener { playAudio() }
        iv_audio_delete.setOnClickListener { deleteAudio() }
        lv_address.setOnClickListener {
            val build = ARouter.getInstance().build("/app/map")
            latitude?.let {
                build.withDouble("latitude", it)
            }
            longitude?.let {
                build.withDouble("longitude", it)
            }
            build.navigation(this, 1010)
        }
    }

    override fun onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        JZVideoPlayer.releaseAllVideos()
    }

    /**
     * 选择图片
     */
    private fun choosePhoto() {
        Album.image(this) // 选择图片。
                .multipleChoice()
                .requestCode(REQUEST_CODE)
                .camera(true)
                .columnCount(3)
                .selectCount(8)
                .checkedList(checkedPhotoList)
                .onResult({ _, result ->
                    checkedPhotoList.clear()
                    checkedPhotoList.addAll(result)
                    photo_list.visibility = if (checkedPhotoList.size > 0) View.VISIBLE else View.GONE
                    commonAdapter!!.notifyDataSetChanged()
                })
                .start()
    }


    /**
     * 显示录音
     */
    private fun showRecord() {
        QMUIKeyboardHelper.hideKeyboard(et_message)
        if (record_audio_panel.visibility == View.VISIBLE) {
            record_audio_panel.visibility = View.GONE
        } else {
            record_audio_panel.visibility = View.VISIBLE
        }
    }


    private fun recordVideo() {
        Album.video(this) // 选择视频。
                .singleChoice()
                .requestCode(REQUEST_CODE)
                .camera(false)
                .columnCount(3)
                .filterSize { attributes -> attributes!! >= 1024 * 1024 * 10 }
                .onResult({ requestCode, result ->
                    checkedVideoList = result
                    val albumFile = checkedVideoList!![0]
                    video_content.visibility = if (checkedVideoList!!.size > 0) View.VISIBLE else View.GONE
                    GlideApp.with(this@RecordActivity).load(albumFile.thumbPath).centerCrop().into(video_thumb)
                })
                .start()
    }

    private fun playAudio() {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer.create(this, Uri.fromFile(File(audioFileName!!)))
        }
        if (mediaPlayer!!.isPlaying) {
            mediaPlayer!!.stop()
            mediaPlayer = null
        } else {
            mediaPlayer!!.start()
        }
    }


    fun deleteAudio() {
        isHasAudio = true
        audio_content.visibility = View.GONE
    }

    private fun saveRecord() {
        if (lastRecordGroup != null) {

            if (record != null) {
                val message = et_message.text.toString()

                val recordBean = record!!

                if (TextUtils.isEmpty(message)) {
                    showTips("请输入现场描述", QMUITipDialog.Builder.ICON_TYPE_INFO)
                    return
                }

                recordBean.message = message
                recordBean.address = address
                recordBean.latitude = latitude.toString()
                recordBean.longitude = longitude.toString()
                val loading = getLoading("正在保存")
                loading.show()
                if (checkedPhotoList.size > 0) {
                    val photos = checkedPhotoList.indices
                            .map { checkedPhotoList[it] }
                            .map { it.path }
                    recordBean.photos = (photos)
                }
                if (audioFileName != null) {
                    recordBean.audio = audioFileName
                }

                if (checkedVideoList.size > 0) {
                    val albumFile = checkedVideoList[0]
                    recordBean.video = (albumFile.path)
                    recordBean.videoThumb = (albumFile.thumbPath)
                }
                recordRepository.saveRecord(recordBean)

                et_message.postDelayed({
                    hideLoading(loading);
                    showTips("本地保存成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS, object : Callback {
                        override fun onSuccess() {
                            finish()
                        }
                    })
                }, 1500)
            } else {
                val message = et_message.text.toString()
                val loadUser = userRepos.loadUser()
                val recordBean = RecordBean()
                recordBean.user_id = loadUser!!.id
                recordBean.created_at = Date()

//                recordBean.record_no = StringUtil.createdRecordNo(lastRecordGroup!!.record_num, loadUser!!.id) + "_" + (recordCount + countLocalRecord)

                recordBean.record_date = lastRecordGroup!!.record_date!!
                recordBean.record_num = lastRecordGroup!!.record_num
                recordBean.record_username = lastRecordGroup!!.record_username
                recordBean.record_people = lastRecordGroup!!.record_people


                if (TextUtils.isEmpty(message)) {
                    showTips("请输入现场描述", QMUITipDialog.Builder.ICON_TYPE_INFO)
                    return
                }



                recordBean.message = message
                val loading = getLoading("正在保存")
                loading.show()
                recordBean.address = address
                recordBean.latitude = latitude.toString()
                recordBean.longitude = longitude.toString()

                if (checkedPhotoList.size > 0) {
                    val photos = checkedPhotoList.indices
                            .map { checkedPhotoList[it] }
                            .map { it.path }
                    recordBean.photos = (photos)
                }

                if (checkedVideoList.size > 0) {
                    val albumFile = checkedVideoList[0]
                    recordBean.video = (albumFile.path)
                    recordBean.videoThumb = (albumFile.thumbPath)
                }
                if (audioFileName != null) {
                    recordBean.audio = audioFileName
                }
                recordRepository.saveRecord(recordBean)

                et_message.postDelayed({
                    hideLoading(loading);
                    showTips("本地保存成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS, object : Callback {
                        override fun onSuccess() {
                            finish()
                        }
                    })

                }, 1500)
            }

        }

    }


    override fun initLayout() {
        setContentView(R.layout.activity_record)
    }

    override fun onRecordPrepare(): Boolean {

        return true
    }

    override fun onRecordStart(): String {
        recordTotalTime = 0
        initTimer()
        timer!!.schedule(timerTask, 0, DEFAULT_MIN_TIME_UPDATE_TIME.toLong())
        audioFileName = App.inst.externalCacheDir!!.path + File.separator + createAudioName()
        horvoiceview.startRecord()
        return audioFileName!!

    }


    /**
     * 初始化计时器用来更新倒计时
     */
    private fun initTimer() {
        timer = Timer()
        timerTask = object : TimerTask() {
            override fun run() {
                mainHandler!!.post {
                    //每隔1000毫秒更新一次ui
                    recordTotalTime += 1000
                    updateTimerUI()
                }
            }
        }
    }

    private fun updateTimerUI() {
        if (recordTotalTime >= maxRecordTime) {
            btn_recordAudio.invokeStop()
        } else {
            val string = String.format(" 倒计时 %s ", StringUtil.formatRecordTime(recordTotalTime, maxRecordTime))
            horvoiceview.setText(string)
        }
    }

    override fun onRecordStop(): Boolean {
        if (recordTotalTime >= minRecordTime) {
            timer!!.cancel()
            horvoiceview.stopRecord()
            horvoiceview.visibility = View.INVISIBLE
            txt_record.text = "长按录音"

            val time = StringUtil.formatTime(recordTotalTime.toInt())
            tv_audio_time.text = time
            isHasAudio = true
            audio_content.visibility = View.VISIBLE
        } else {
            onRecordCancel()
        }
        return false
    }

    override fun onRecordCancel(): Boolean {
        if (timer != null) {
            timer!!.cancel()
        }
        updateCancelUi()
        return false
    }

    private fun updateCancelUi() {
        horvoiceview.visibility = View.INVISIBLE
        txt_record.text = "长按录音"
        horvoiceview.stopRecord()
        deleteTempFile()
    }

    private fun deleteTempFile() {
        //取消录制后删除文件
        if (audioFileName != null) {
            val tempFile = File(audioFileName!!)
            if (tempFile.exists()) {
                tempFile.delete()
            }
        }
    }

    override fun onSlideTop() {
        horvoiceview.visibility = View.INVISIBLE
//        txt_record.visibility = View.INVISIBLE
    }

    override fun onFingerPress() {
        horvoiceview.visibility = View.VISIBLE
        txt_record.visibility = View.VISIBLE
    }

    private fun createAudioName(): String {
        val time = System.currentTimeMillis()
        return UUID.randomUUID().toString() + time + ".amr"
    }

    companion object {
        private val REQUEST_CODE = 1001
        val DEFAULT_MAX_RECORD_TIME: Long = 600000
        val DEFAULT_MIN_RECORD_TIME: Long = 2000
        protected val DEFAULT_MIN_TIME_UPDATE_TIME = 1000
    }
}
